local CommonOHOH = _G.CommonOHOH;
local game_cfg = CommonOHOH.config.Game
local M={}

-- 递归好友列表
local function iterPageItems(pages)
	return coroutine.wrap(function()
		local pagenum = 1
		while true do
			for _, item in ipairs(pages:GetCurrentPage()) do
				coroutine.yield(item, pagenum)
			end
			if pages.IsFinished then
				break
			end
			pages:AdvanceToNextPageAsync()
			pagenum = pagenum + 1
		end
	end)
end
function FindFriend(player,OnLineCount,OffLineCount)
	local OnLine={}
	local OffLine={}
	local friendPages =game.Players:GetFriendsAsync(player.UserId)
	for item, pageNo in iterPageItems(friendPages) do
		if  item.IsOnline then
			table.insert(OnLine,{
				UserId=item.Id,
				UserName=item.Username,
			})
			OnLineCount=OnLineCount-1

			-- warn("Online:",item.Id,item.Username)
		else
			table.insert(OffLine,{
				UserId=item.Id,
				UserName=item.Username,
			})

			-- warn("OffLine:",item.Id,item.Username)
			OffLineCount=OffLineCount-1

		end

		if OnLineCount<=0 and OffLineCount<=0 then
			return OnLine,OffLine
		end
		if #OffLine>200 then --最多拉取200个离线好友
			return 
		end
	end

	return OnLine,OffLine
end


function M.CreateFriendBuffer(player)
	local a1,a2=FindFriend(player,game_cfg.OnLineFriendLoadCount,game_cfg.OfflineFriendLoadCount)
	return {
		lastTime=os.time(),
		online=a1,
		offline=a2,
		obj=player,
		GetOnLineFriend=function(this)
			if  os.time()-this.lastTime>game_cfg.FriendRefreshTime then
				local x1,x2=FindFriend(this.obj,game_cfg.OnLineFriendLoadCount,game_cfg.OfflineFriendLoadCount)
				this.online=x1
				this.offline=x2
				this.lastTime=os.time()
			end
			return this.online
		end,

		GetOfflineFirend=function(this)
			if  os.time()-this.lastTime>game_cfg.FriendRefreshTime then
				local x1,x2=FindFriend(this.obj,game_cfg.OnLineFriendLoadCount,game_cfg.OfflineFriendLoadCount)
				this.online=x1
				this.offline=x2
				this.lastTime=os.time()
			end

			return this.offline
		end

	}
end


return M